package controller;

import java.util.Random;

import modele.Square;
import modele.World;
import modele.WorldElem.Earth;
import modele.WorldElem.Grass;
import modele.WorldElem.None;
import modele.WorldElem.Rock;
import modele.WorldElem.Sand;
import modele.WorldElem.SecondaryState;
import modele.WorldElem.Tree;
import modele.WorldElem.WaterSource;

public class NaturalEvolutionRule1 extends Rule{

	public NaturalEvolutionRule1(World w) {
		super(w);
	}

	@Override
	public void applyRule(Earth e, Square s) {
		if(s.getSecondaryStateValue() == SecondaryState.NONE){
			None n = (None) s.getSecondaryState();
			if(n.getNoneTime() > Earth.TOGRASS){
				Random r = new Random();
				if(r.nextFloat() < 0.04* (float)(n.getNoneTime()-Earth.TOGRASS)){
					Grass g = new Grass();
					s.setState(g);
				}
			}
			else{
				n.setNoneTime(n.getNoneTime()+1);
			}
		}
		else
			getEvolvedSquareMap()[s.getPosX()][s.getPosY()]=null;
	}

	@Override
	public void applyRule(Grass g, Square s) {
		if(s.getSecondaryStateValue() == SecondaryState.NONE){
			None n = (None) s.getSecondaryState();
			if(n.getNoneTime() > Grass.TOTREE){
				Random r = new Random();
				if(r.nextFloat() < Math.pow(getWorld().getWidth(), 3) * (double)(n.getNoneTime() - Grass.TOTREE)){
					Tree t = new Tree();
					s.setState(t);
				}
				else{
					((None) s.getSecondaryState()).setNoneTime(0);
				}
			}
			else{
				n.setNoneTime(n.getNoneTime()+1);
			}
		}
		else
			getEvolvedSquareMap()[s.getPosX()][s.getPosY()]=null;
	}

	@Override
	public void applyRule(Rock r, Square s) {
		if(s.getSecondaryStateValue() == SecondaryState.NONE){
			None n = (None) s.getSecondaryState();
			n.setNoneTime(n.getNoneTime()+1);
		}
		else
			getEvolvedSquareMap()[s.getPosX()][s.getPosY()]=null;
	}

	@Override
	public void applyRule(Sand sa, Square s) {
		if(s.getSecondaryStateValue() == SecondaryState.NONE){
			None n = (None) s.getSecondaryState();
			n.setNoneTime(n.getNoneTime()+1);
		}
		else
			getEvolvedSquareMap()[s.getPosX()][s.getPosY()]=null;	
	}

	@Override
	public void applyRule(Tree t, Square s) {
		if(s.getSecondaryStateValue() == SecondaryState.NONE){
			None n = (None) s.getSecondaryState();
			n.setNoneTime(n.getNoneTime()+1);
		}
		else
			getEvolvedSquareMap()[s.getPosX()][s.getPosY()]=null;		
	}

	@Override
	public void applyRule(WaterSource ws, Square s) {
		getEvolvedSquareMap()[s.getPosX()][s.getPosY()]=null;		
	}

	@Override
	public void prepareToEvolve() {
		setEvolvedSquareMap(getWorld().cloneSquareMap());
	}

	@Override
	public int getRuleValue() {
		return Rule.NATURALEVOLUTION;
	}

}
